(function ($) {
	
	$.zjb_dialog = {};
	
	/**
	 * 打开对话框
	 * options		配置参数, 包含
	 * 		width		宽
	 * 		height		高
	 * 		title		标题
	 * 		content		内容
	 * 		buttons		按钮清单, 为数组, 每个元素包含
	 * 			name		按钮文本
	 * 			callback	回调函数
	 * 			isDefault	是否为默认按钮
	 * 		onLoad		对话框加载完毕回调函数, 形式
	 * 			function (dialog)
	 * 					其中 dialog 为对话框本体 
	 */
	function openDialog(options) {
		function bindClick(func, element, dialog) {
			element.click(function () {
				if (!!func && typeof func == 'function')
					func(dialog);
			});
		}
		
		var div = $('<div>');
		
		var html = [];
		html.push('<div class="zjbDlgMask"></div>');
		html.push('<div class="zjbDlgBody">');
		html.push('		<div class="zjbDlgTitle subsubtitle">' + options.title + '</div>');
		html.push('		<div class="zjbDlgContent"></div>');
		html.push('		<div class="zjbDlgFooter rightingText"></div>');
		html.push('</div>');
		
		$('body').append(div);
		div.addClass('zjbDlg');
		div.html(html.join('\r\n'));
		div.attr('tabIndex', '0');
		
		if (!!options.width) {
			div.find('.zjbDlgBody').css({
				width: options.width + 'px',
				'margin-left': ( -options.width / 2 - 4) + 'px'
			});
		}
		
		if (options.height <= 240)
			options.height = 240;
		
		div.find('.zjbDlgBody').css({
			height: options.height + 'px',
			'margin-top': ( -options.height / 2 - 16) + 'px'
		});
		
		div.find('.zjbDlgBody>.zjbDlgContent').css({
			height: (options.height - 76) + 'px'
		});
		
		var contentDiv = div.find('.zjbDlgBody>.zjbDlgContent');
		if (typeof options.content == 'string')
			contentDiv.html(options.content);
		else
			contentDiv.append(options.content);
		
		var buttons = options.buttons;
		var buttonsDiv = div.find('.zjbDlgFooter');
		
		for (var i=0; i<buttons.length; i++) {
			var button = buttons[i];
			var bDiv = $('<span class="zjbDlgButton button">' + button.name + '</span>');
			if (!!button.isDefault)
				bDiv.addClass('default');
			buttonsDiv.append(bDiv);
			bindClick(button.callback, bDiv, div);
		}
		
		if (!!options.onLoad && typeof options.onLoad == 'function') {
			setTimeout(() => options.onLoad(div), 0);
		}
		
		return div;
	}
	
	/**
	 * 关闭对话框
	 * @param dialog
	 * @returns
	 */
	function closeDialog(dialog) {
		dialog.remove();
	}
	
	$.zjb_dialog.defaults = {
		width: null,
		height: null,
		title: '(无)',
		content: '(无)',
		buttons: [
			{ name: '关闭', isDefault: true, callback: closeDialog }
		],
		onLoad: function (dialog) {}
	};
	
	$.zjb_dialog.alert = function (title, content, callback, options) {
		var done = dialog => {
			closeDialog(dialog);
			if (!!callback && typeof callback == 'function')
				callback();
		};
		
		return openDialog($.extend({
			title: title,
			content: content,
			buttons: [
				{ name: '关闭', isDefault: true, callback: done }
			],
			onLoad: dialog => {
				dialog.focus();
				dialog.keydown(evt => {
					if (evt.keyCode == 27) done(dialog);
				});
			}
		}, options || {}));
	};
	
	$.zjb_dialog.confirm = function (title, content, callback, options) {	
		var done = result => dialog => {
			closeDialog(dialog);
			if (!!callback && typeof callback == 'function')
				callback(result);
		};
		
		return openDialog($.extend({
			title: title,
			content: content,
			buttons: [
				{ name: '确定', isDefault: true, callback: done(true) },
				{ name: '取消', callback: done(false) }
			],
			onLoad: dialog => {
				dialog.keydown(evt => {
					if (evt.keyCode == 27) done(false)(dialog);
				});
			}
		}, options || {}));
	};
	
	$.zjb_dialog.input = function (title, defaultValue, callback, options) {
		var okCB = dialog => {
			var text = contentDiv.val() || '';
			closeDialog(dialog);
			if (!!callback && typeof callback == 'function')
				callback(text);
		};
				
		var contentDiv = $('<input type="text" class="zjbDlgInput centeringText" />');
		
		return openDialog($.extend({
			title: title,
			content: contentDiv,
			buttons: [
				{ name: '确定', isDefault: true, callback: okCB },
				{ name: '取消', callback: closeDialog }
			],
			onLoad: dialog => {
				contentDiv.val(defaultValue || '').focus();
				contentDiv.keydown(evt => {
					if (evt.keyCode == 13)
						okCB(dialog);
					else if (evt.keyCode == 27)
						closeDialog(dialog);
				});
			}
		}, options || {}));
	};
	
	$.zjb_dialog.textarea = function (title, defaultValue, callback, options) {
		var okCB = dialog => {
			var text = contentDiv.val() || '';
			closeDialog(dialog);
			if (!!callback && typeof callback == 'function')
				callback(text);
		};
		
		var contentDiv = $('<textarea type="text" class="zjbDlgTextArea centeringText"></textarea>');
		
		return openDialog($.extend({
			title: title,
			content: contentDiv,
			buttons: [
				{ name: '确定', isDefault: true, callback: okCB },
				{ name: '取消', callback: closeDialog }
			],
			onLoad: dialog => {
				contentDiv.val(defaultValue || '').focus()
				contentDiv.keydown(evt => {
					if (evt.keyCode == 13 && !!evt.ctrl)
						okCB(dialog);
					else if (evt.keyCode == 27)
						closeDialog(dialog);
				});
			}
		}, options || {}));
	}; 
	
	$.zjb_dialog.password = function (title, defaultValue, callback, options) {
		var okCB = dialog => {
			var password = contentDiv.val() || '';
			closeDialog(dialog);
			if (!!callback && typeof callback == 'function')
				callback(password);
		};
			
		var contentDiv = $('<input type="password" class="zjbDlgInput centeringText" />');
		
		return openDialog($.extend({
			title: title,
			content: contentDiv,
			buttons: [
				{ name: '确定', isDefault: true, callback: okCB },
				{ name: '取消', callback: closeDialog }
			],
			onLoad: dialog => {
				contentDiv.val(defaultValue || '').focus()
				contentDiv.keydown(evt => {
					if (evt.keyCode == 13)
						okCB(dialog);
					else if (evt.keyCode == 27)
						closeDialog(dialog);
				});
			}
		}, options || {}));
	};
	
	$.zjb_dialog.viewInfo = function (title, url, callback, options) {
		var okCB = dialog => {
			closeDialog(dialog);
			if (!!callback && typeof callback == 'function')
				callback();
		};
		
		var contentDiv = $('<div class="zjbDialogInfo" style="overflow-y: auto;"></div>');
		
		return openDialog($.extend({
			title: title,
			content: contentDiv,
			width: 800,
			height: 640,
			buttons: [
				{ name: '关闭', isDefault: true, callback: okCB }
			],
			onLoad: dialog => {
				contentDiv.load(url);
				dialog.keydown(evt => {
					if (evt.keyCode == 27)
						okCB(dialog);
				});
			}
		}, options || {}));
	};
	
	$.zjb_dialog.select = function (title, items, selected, callback, options) {
		var defaultOptions = {
			valueSelector: x => x,
			textSelector: x => x,
			singleSelect: true
		};
		
		var generateItem = (item, selected, valueSelector, textSelector, itemClickCallback) => {
			var html = [];
			html.push('<div class="zjbDlgItem" tagText="' + textSelector(item) + '" tagValue="' + valueSelector(item) + '">' + textSelector(item) + '</div>');
			var div = $(html.join('\r\n'));

			div.data('zjbDlgItem', item);
			div.click(() => itemClickCallback(item));
			
			if (!!selected && !!selected[textSelector(item)])
				div.attr('selected', 'selected');
			
			return div;
		};
		
		var generateContent = (items, selected, options, itemClickCallback, fakeItemClickCallback) => {
			var html = [];
			html.push('<div class="zjbDlgList"></div>');
			var div = $(html.join('\r\n'));
			for (var i=0; i<items.length; i++) {
				var iDiv = generateItem(items[i], selected, options.valueSelector, options.textSelector, item => itemClickCallback(div, item, options));
				div.append(iDiv);
			}
			if (options.allowHandWrite) {
				var fakeCallback = fakeItemClickCallback || (() => {});
				var otherItem = { _name: '其它', _fake: true };
				var otherDiv = generateItem(otherItem, [], x => x._name, x => x._name, fakeCallback);
				div.append(otherDiv);
			}
			div.append('<div class="clear"></div>');
			return div;
		};
		
		var selectItem = (containerDiv, item, options) => {			
			var allDiv = containerDiv.find('.zjbDlgItem');
			var selectedDiv = allDiv.filter('[tagText="' + options.textSelector(item) + '"]');
			var currentValue = !!selectedDiv.attr('selected');
			
			if (!!options.singleSelect)
				allDiv.removeAttr('selected');
						
			var attrSwitchers = {
				true: target => target.removeAttr('selected'), 
				false: target => target.attr('selected', 'selected')
			};
			attrSwitchers[currentValue](selectedDiv);
		};
		
		var gethorData = containerDiv => {
			var allDiv = containerDiv.find('.zjbDlgItem[selected]');
			var items = [];
			allDiv.each((index, div) => items.push($(div).data('zjbDlgItem')));
			return items;
		};
		
		var okCB = dialog => {
			var selected = gethorData(contentDiv);
			closeDialog(dialog);
			if (typeof callback == 'function')
				callback(selected);
		};
		
		var fakeOKCB = item => {
			$.zjb_dialog.input('请输入其它项目的具体内容', '', text => {
				closeDialog(thisDialog);
				item._value = text;
				if (typeof callback == 'function')
					callback(item);
			});
		};
		
		var opt = $.extend({}, defaultOptions, options);
		var contentDiv = generateContent(items, selected, opt, selectItem, fakeOKCB);
		var thisDialog = null;
		
		openDialog($.extend({
			title: title,
			content: contentDiv,
			width: 480,
			height: 320,
			buttons: [
				{ name: '确定', isDefault: true, callback: okCB, }, 
				{ name: '取消', callback: closeDialog }
			],
			onLoad: dialog => {
				thisDialog = dialog; 
				dialog.focus();
				dialog.keydown(evt => {
					if (evt.keyCode == 27)
						closeDialog(dialog);
				});
			}
		}, options || {}))
	};
	
	$.zjb_dialog.createDialog = function (options) {
		return openDialog(options);
	};
	
	$.zjb_dialog.removeDialog = function (dialog) {
		return closeDialog(dialog);
	};
	
})(jQuery);